﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Radiation___IM;
using System.Windows.Forms;

namespace RadiationUI
{
    public class AsyncAPI
    {
        private static AsyncAPI _instance;

        public static void Init()
        {
            _instance = new AsyncAPI();
        }

        public static AsyncAPI Instance
        {
            get { return _instance; }
        }

        // Dynamic part 

        private ManualResetEvent m_api_event;
        private MessageParser m_last_message;

        public ManualResetEvent Event
        {
            get
            {
                return m_api_event;
            }
        }

        public MessageParser LastMessage
        {
            get
            {
                return m_last_message;
            }
        }

        public AsyncAPI()
        {
            m_api_event = new ManualResetEvent(false);
            m_last_message = null;
        }

        public void signal(MessageParser message)
        {
            this.m_last_message = message;
            Thread.Sleep(50);
            this.m_api_event.Set();
        }

        public MessageParser waitSignal()
        {
            this.m_api_event.Reset();
            this.m_api_event.WaitOne();
            return this.m_last_message;
        }

        public MessageParser waitSignal(int timeout_second)
        {
            try
            {
                this.m_api_event.Reset();
                this.m_api_event.WaitOne(timeout_second * 1000);
                return this.m_last_message;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
